package com.example.webdemo.utils;

import android.util.Base64;
import java.security.SecureRandom;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AesUtils {

    private static volatile AesUtils mInstance;

    public static AesUtils getInstance() {
        if (mInstance == null) {
            synchronized (AesUtils.class) {
                if (mInstance == null) {
                    mInstance = new AesUtils();
                }
            }
        }
        return mInstance;
    }


    /**
     * 生成一个 AES 128 位密钥，并返回 Base64 编码的字符串
     */
    public String generateBase64Key() {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom());
            SecretKey skey = kgen.generateKey();
            byte[] raw = skey.getEncoded();
            return Base64.encodeToString(raw, Base64.NO_WRAP);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * AES 加密（ECB 模式，PKCS5Padding）
     *
     * @param data      明文字符串
     * @param base64Key Base64 编码的 AES 密钥（16 字节）
     * @return 加密后 Base64 编码的字符串
     */
    public String encrypt(String data, String base64Key) {
        try {
//            byte[] keyBytes = Base64.decode(base64Key, Base64.NO_WRAP);
            byte[] keyBytes = base64Key.getBytes("UTF-8");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.encodeToString(encrypted, Base64.NO_WRAP)
                    .replace("=", ""); //处理Base64补"="的问题
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * AES 解密（ECB 模式，PKCS5Padding）
     *
     * @param base64Data Base64 编码的密文
     * @param base64Key  Base64 编码的 AES 密钥
     * @return 解密后的明文字符串
     *
     */
    public String decrypt(String base64Data, String base64Key) {
        try {
//            byte[] keyBytes = Base64.decode(base64Key, Base64.NO_WRAP);
            byte[] keyBytes = base64Key.getBytes("UTF-8");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decodedData = Base64.decode(base64Data, Base64.NO_WRAP);
            byte[] decrypted = cipher.doFinal(decodedData);
            return new String(decrypted, "UTF-8");
        } catch (Exception e) {
            return null;
        }
    }


    // 生成10位随机字符串（数字 + 字母）
    public String getRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

}
